/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufba.lasid.v1.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import org.apache.thrift.TDeserializer;

/**
 *
 * @author Felipe Oliveira Gutierrez
 */
public class ReceiveVMMetricObservations {

	private static final String EXCHANGE_NAME = "vm_metric";
	private static final String EXCHANGE_TYPE = "topic";

	/**
	 * 
	 * Exemplo de Uso:
	 * 
	 * sh run-publisher.sh
	 * br.ufba.lasid.v2.msgqueue.ReceiveVMMetricObservations "#"
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {

		// obtém uma conexão para acesso ao servidor AMQP
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost(AMQPProperties.get(AMQPProperties.HOST));
		factory.setPort(Integer.parseInt(AMQPProperties
				.get(AMQPProperties.PORT)));
		Connection connection = factory.newConnection();

		// obtém uma canal, uma forma de multiplexar uma mesma conexão
		Channel channel = connection.createChannel();

		// channel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE);
		channel.queueDeclare(EXCHANGE_NAME, false, false, false, null);

		// fila onde ficarão as mensagens recebidas
		String queueName = channel.queueDeclare().getQueue();

		if (args.length < 1) {
			System.err
					.println("Usage: ReceiveVMMetricObservations [binding_key]...");
			System.exit(1);
		}

		// for (String bindingKey : args) {
		// channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);
		// }

		System.out
				.println(" [*] Waiting for metric observations. To exit press CTRL+C");

		QueueingConsumer consumer = new QueueingConsumer(channel);
		// channel.basicConsume(queueName, true, consumer);
		// Register the consumer on the channel
		channel.basicConsume(EXCHANGE_NAME, true, consumer);

		while (true) {
			QueueingConsumer.Delivery delivery = consumer.nextDelivery();
			// String message = new String(delivery.getBody());
			// String routingKey = delivery.getEnvelope().getRoutingKey();
			//
			// System.out.println(" [x] Received '" + routingKey + "':'" +
			// message + "'");
			// Create a empty notification (we will fill this with the
			// contents of the Thrift serialized payload)

			Item item = new Item();
			// Instantiate the Thrift Deserializer
			TDeserializer deserializer = new TDeserializer();
			// Deserialize the body of the AMQP message, setting the state
			// on the empty notification object
			deserializer.deserialize(item, delivery.getBody());

			// Print the notification to the console.
			System.out.println(" [x] Received '" + item.toString() + "'");
		}
		// channel.close();
		// connection.close();
	}
}